package com.srmt.document.feishu.internal.writer;

import com.lark.oapi.service.docx.v1.model.Block;
import com.srmt.document.exception.TableException;
import com.srmt.document.feishu.internal.core.BlockContext;
import com.srmt.document.feishu.internal.table.TableOperationStrategy;
import com.srmt.document.feishu.internal.table.TableStrategyFactory;
import com.srmt.document.feishu.internal.table.model.TableContext;
import com.srmt.document.model.RowData;
import com.srmt.feishu.client.FeishuClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 表格行操作服务
 *
 * 负责处理表格的行级操作：添加行、追加行、删除行
 *
 * @author SRMT Development Team
 * @since 2.0.0
 */
public class TableRowOperationService {

    private static final Logger logger = LoggerFactory.getLogger(TableRowOperationService.class);

    private final FeishuClient client;
    private final TableStrategyFactory strategyFactory;

    /**
     * 构造函数
     *
     * @param client 飞书客户端
     */
    public TableRowOperationService(FeishuClient client) {
        if (client == null) {
            throw new IllegalArgumentException("客户端不能为null");
        }
        this.client = client;
        this.strategyFactory = TableStrategyFactory.create(client);
    }

    /**
     * 在指定位置添加表格行
     *
     * @param docId 文档ID
     * @param anchorText 锚点文本
     * @param rows 行数据列表
     * @param startRow 起始行索引（-1表示追加到末尾）
     * @throws TableException 如果操作失败
     */
    public void addTableRowsAfter(String docId, String anchorText, List<RowData> rows, int startRow)
            throws TableException {
        logger.debug("向锚点后的表格添加{}行 '{}' at row {}",
                    rows.size(), anchorText, startRow);

        try {
            // 创建上下文
            BlockContext context = new BlockContext(client, docId);

            // 查找表格
            Block tableBlock = context.findTableAfterAnchor(anchorText);
            if (tableBlock == null) {
                throw new TableException("锚点后未找到表格: " + anchorText);
            }


            // 创建表格上下文
            TableContext tableContext = new TableContext(docId, context, tableBlock);

            // 获取对应的策略
            TableOperationStrategy strategy = this.strategyFactory.getStrategy(tableBlock);

            // 委托给策略执行添加行操作
            strategy.addTableRows(tableContext, rows, startRow);

            logger.info("成功向表格添加{}行", rows.size());

        } catch (TableException e) {
            throw e;
        } catch (Exception e) {
            throw new TableException("添加表格行失败: " + e.getMessage());
        }
    }

    /**
     * 追加表格行到末尾
     *
     * @param docId 文档ID
     * @param anchorText 锚点文本
     * @param rows 行数据列表
     * @throws TableException 如果操作失败
     */
    public void appendTableRowsAfter(String docId, String anchorText, List<RowData> rows)
            throws TableException {
        logger.debug("在锚点'{}'后向表格追加{}行 '{}'", rows.size(), anchorText);
        addTableRowsAfter(docId, anchorText, rows, -1);
    }

    /**
     * 删除表格行
     *
     * @param docId 文档ID
     * @param tableAnchor 表格锚点文本
     * @param startRow 起始行索引
     * @param endRow 结束行索引（包含）
     * @throws TableException 如果操作失败
     */
    public void deleteTableRows(String docId, String tableAnchor, int startRow, int endRow)
            throws TableException {
        logger.debug("删除 rows {} to {} from table with anchor '{}'",
                    startRow, endRow, tableAnchor);

        try {
            // 创建上下文
            BlockContext context = new BlockContext(client, docId);

            // 查找表格
            Block tableBlock = context.findTableAfterAnchor(tableAnchor);
            if (tableBlock == null) {
                throw new TableException("锚点后未找到表格: " + tableAnchor);
            }

            // 创建表格上下文
            TableContext tableContext = new TableContext(docId, context, tableBlock);

            // 获取合适的策略并执行删除操作
            TableOperationStrategy strategy = this.strategyFactory.getStrategy(tableBlock);
            strategy.deleteTableRows(tableContext, startRow, endRow);

            logger.info("删除d rows {} to {} from table", startRow, endRow);

        } catch (Exception e) {
            if (e instanceof TableException) {
                throw (TableException) e;
            }
            throw new TableException("删除表格行失败: " + e.getMessage());
        }
    }
}
